<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="计划名称" prop="planName">
            <el-input
                v-model="queryParams.planName"
                placeholder="请输入计划名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备ID" prop="deviceId">
            <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入设备ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="planType">
            <template #label>
              <el-tooltip content="计划类型: 1-定期维护, 2-预防性维护, 3-临时维护" placement="top">
                <span>计划类型 <el-icon><InfoFilled /></el-icon></span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.planType" placeholder="请选择计划类型" clearable style="width: 100%;">
              <!-- 修正：v-for 和所有属性都在 el-option 的开始标签内 -->
              <el-option
                  v-for="dict in plan_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="status">
            <template #label>
              <el-tooltip content="状态: 0-未开始, 1-进行中, 2-已暂停, 3-已取消, 4-已完成" placement="top">
                <span>状态 <el-icon><InfoFilled /></el-icon></span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%;">
              <!-- 修正：v-for 和所有属性都在 el-option 的开始标签内 -->
              <el-option
                  v-for="dict in plan_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker clearable
                            v-model="queryParams.startDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择开始日期"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker clearable
                            v-model="queryParams.endDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择结束日期"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计耗时" prop="estimatedHours">
            <el-input
                v-model="queryParams.estimatedHours"
                placeholder="请输入预计耗时(小时)"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="pstatus">
            <template #label>
              <el-tooltip content="发布状态: 0-未发布, 1-发布" placement="top">
                <span>发布状态 <el-icon><InfoFilled /></el-icon></span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.pstatus" placeholder="请选择发布状态" clearable style="width: 100%;">
              <!-- 修正：v-for 和所有属性都在 el-option 的开始标签内 -->
              <el-option
                  v-for="dict in is_release"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="search-buttons-aligned">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['maintenance:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['maintenance:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['maintenance:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['maintenance:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划ID" align="center" prop="id" width="80" />
      <el-table-column label="计划名称" align="center" prop="planName" min-width="150px" :show-overflow-tooltip="true" />
      <el-table-column label="设备ID" align="center" prop="deviceId" width="100" />
      <el-table-column prop="planType" align="center" min-width="120px">
        <template #header>
          <el-tooltip content="计划类型: 1-定期维护, 2-预防性维护, 3-临时维护" placement="top">
            <span>计划类型 <el-icon><InfoFilled /></el-icon></span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="plan_type" :value="scope.row.planType"/>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 维护内容字段优化：剥离HTML，截断显示，悬停显示全部 -->
      <el-table-column label="维护内容" align="center" prop="content" min-width="200px">
        <template #default="scope">
          <span v-if="scope.row.content">
            <el-tooltip :content="stripHtmlTags(scope.row.content)" placement="top">
              <span class="truncated-text">{{ stripHtmlTags(scope.row.content) }}</span>
            </el-tooltip>
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="预计耗时(h)" align="center" prop="estimatedHours" width="120" />
      <el-table-column prop="status" align="center" min-width="100px">
        <template #header>
          <el-tooltip content="状态: 0-未开始, 1-进行中, 2-已暂停, 3-已取消, 4-已完成" placement="top">
            <span>状态 <el-icon><InfoFilled /></el-icon></span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="plan_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column prop="pstatus" align="center" min-width="100px">
        <template #header>
          <el-tooltip content="发布状态: 0-未发布, 1-发布" placement="top">
            <span>发布 <el-icon><InfoFilled /></el-icon></span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="is_release" :value="scope.row.pstatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['maintenance:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['maintenance:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改维护计划对话框 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item prop="planType">
          <template #label>
            <el-tooltip content="计划类型: 1-定期维护, 2-预防性维护, 3-临时维护" placement="top">
              <span>计划类型 <el-icon><InfoFilled /></el-icon></span>
            </el-tooltip>
          </template>
          <el-select v-model="form.planType" placeholder="请选择计划类型" style="width: 100%;">
            <!-- 修正：v-for 和所有属性都在 el-option 的开始标签内 -->
            <el-option
                v-for="dict in plan_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
                          v-model="form.startDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开始日期"
                          style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
                          v-model="form.endDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结束日期"
                          style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维护内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="预计耗时(小时)" prop="estimatedHours">
          <el-input v-model="form.estimatedHours" placeholder="请输入预计耗时(小时)" />
        </el-form-item>
        <el-form-item prop="status">
          <template #label>
            <el-tooltip content="状态: 0-未开始, 1-进行中, 2-已暂停, 3-已取消, 4-已完成" placement="top">
              <span>状态 <el-icon><InfoFilled /></el-icon></span>
            </el-tooltip>
          </template>
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
            <!-- 修正：v-for 和所有属性都在 el-option 的开始标签内 -->
            <el-option
                v-for="dict in plan_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="pstatus">
          <template #label>
            <el-tooltip content="发布状态: 0-未发布, 1-发布" placement="top">
              <span>发布状态 <el-icon><InfoFilled /></el-icon></span>
            </el-tooltip>
          </template>
          <!-- 这里无需修正，el-radio-group 的子组件 el-radio 是正确的 -->
          <el-radio-group v-model="form.pstatus">
            <el-radio
                v-for="dict in is_release"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/maintenance/plan"
import { InfoFilled } from '@element-plus/icons-vue' // 引入图标

const { proxy } = getCurrentInstance()
const { plan_type, plan_status, is_release } = proxy.useDict('plan_type', 'plan_status', 'is_release')

const planList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    deviceId: null,
    planType: null,
    startDate: null,
    endDate: null,
    content: null,
    estimatedHours: null,
    status: null,
    pstatus: null,
  },
  rules: {
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
    planType: [
      { required: true, message: "计划类型不能为空", trigger: "change" }
    ],
    startDate: [
      { required: true, message: "开始日期不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "维护内容不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    pstatus: [
      { required: true, message: "发布状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// HTML标签剥离函数
function stripHtmlTags(htmlString) {
  if (!htmlString) return '';
  const doc = new DOMParser().parseFromString(htmlString, 'text/html');
  return doc.body.textContent || '';
}

/** 查询维护计划列表 */
function getList() {
  loading.value = true
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows.map(item => ({
      ...item,
      planType: item.planType !== null ? Number(item.planType) : null,
      status: item.status !== null ? Number(item.status) : null,
      pstatus: item.pstatus !== null ? Number(item.pstatus) : null
    }));
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    planName: null,
    deviceId: null,
    planType: null,
    startDate: null,
    endDate: null,
    content: null,
    estimatedHours: null,
    status: null,
    pstatus: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  }
  proxy.resetForm("planRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.planType = null; // 显式重置
  queryParams.value.status = null;   // 显式重置
  queryParams.value.pstatus = null;  // 显式重置
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加维护计划"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPlan(_id).then(response => {
    response.data.planType = response.data.planType !== null ? Number(response.data.planType) : null;
    response.data.status = response.data.status !== null ? Number(response.data.status) : null;
    response.data.pstatus = response.data.pstatus !== null ? Number(response.data.pstatus) : null;
    form.value = response.data
    open.value = true
    title.value = "修改维护计划"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除维护计划编号为"' + _ids + '"的数据项？').then(function() {
    return delPlan(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('maintenance/plan/export', {
    ...queryParams.value
  }, `plan_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
/* 统一的表单标签和图标样式 */
.el-form-item__label span {
  display: flex;
  align-items: center;
  white-space: nowrap; /* 防止标签文本换行 */
}
.el-form-item__label .el-icon {
  margin-left: 4px; /* 图标与文字间距 */
  font-size: 14px;
  cursor: help; /* 提示可悬浮 */
}

/* 搜索按钮组的对齐样式，清除默认左边距以更好地对齐 */
.search-buttons-aligned {
  margin-left: 0 !important;
  white-space: nowrap; /* 确保按钮不换行 */
}

/* 表格内长文本截断样式 */
.truncated-text {
  display: block; /* 确保占满宽度 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 100%; /* 限制最大宽度 */
}
</style>
